package com.ocom.common.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageTypeChecker {
    public static String getImageType(String filePath) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] buffer = new byte[4];
            bis.read(buffer, 0, 4);
            return getImageTypeFromBytes(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getImageTypeFromBytes(byte[] buffer) {
        if (buffer[0] == (byte) 0xFF && buffer[1] == (byte) 0xD8 && buffer[2] == (byte) 0xFF) {
            return "JPEG";
        } else if (buffer[0] == (byte) 0x89 && buffer[1] == (byte) 0x50 && buffer[2] == (byte) 0x4E && buffer[3] == (byte) 0x47) {
            return "PNG";
        } else if (buffer[0] == (byte) 0x47 && buffer[1] == (byte) 0x49 && buffer[2] == (byte) 0x46 && buffer[3] == (byte) 0x38) {
            return "GIF";
        } else if (buffer[0] == (byte) 0x42 && buffer[1] == (byte) 0x4D) {
            return "BMP";
        } else if (buffer[0] == (byte) 0x66 && buffer[1] == (byte) 0x69 && buffer[2] == (byte) 0x6c && buffer[3] == (byte) 0x65) {
            return "JPG";
        } else {
            return null;
        }
    }
}
